//
//  ZRLampBarController.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/11/20.
//  Copyright © 2018年 zero. All rights reserved.
//  顶部标签栏 控制器


#import "ZRLampBarController.h"
#import "ZRLampCollectionViewCell.h"
#import <objc/runtime.h>

/** 判断是否为 iPhone X */
#define kIsIphoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

/** 状态栏高度 */
#define kStatusBarHeight ([UIApplication sharedApplication].statusBarFrame.size.height)

/** 导航栏 + 状态栏高度 */
#define kNavBarHeight (self.navigationController.navigationBar.hash ? (self.navigationController.navigationBar.frame.size.height + ZRStatusBarHeight) : ZRIsIphoneX ? (88) : (64))

/** 屏幕宽度 */
 #define kScreenW [UIScreen mainScreen].bounds.size.width

/** 屏幕高度 */
#define kScreenH [UIScreen mainScreen].bounds.size.height

/** TabBar 高度 */
#define kTabBarHeight (self.tabBarController.tabBar.frame.size.height)

/** 弱引用self */
#define ZRWeakSelf __weak typeof(self) weakSelf = self;

@interface ZRLampBarController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic , weak) UICollectionViewFlowLayout * flowLayout;
/** 顶部标签栏 */
@property (nonatomic , strong) UICollectionView * lampCollectionView;
/** 指示器 */
@property (nonatomic , strong) UIView * indicatorView;
/** 显示视图 */
@property (nonatomic , strong) UIScrollView * mainScrollView;
/** 选中下标 */
@property (nonatomic , assign) int selectedIndex;
/** 区分 点击动画 和 滑动动画 */
@property (nonatomic , assign) BOOL isSelectedAnimation;

@end

static NSString * const id_cell = @"ZRLampCollectionViewCell";

@implementation ZRLampBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self prepareSetting];
    [self.view addSubview:self.lampCollectionView];
    [self.lampCollectionView addSubview:self.indicatorView];
    [self.view addSubview:self.mainScrollView];
    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.lampCollectionView.frame = CGRectMake(0, _lampBarY, kScreenW, _lampBarHeight);
    
    self.indicatorView.frame = CGRectMake(0, _lampBarHeight - _indicatorHeight, _lampItemWidth, _indicatorHeight);
    
    CGFloat lampCollectionView_Y = CGRectGetMaxY(self.lampCollectionView.frame);
    self.mainScrollView.frame = CGRectMake(0, lampCollectionView_Y, kScreenW, kScreenH - lampCollectionView_Y - kTabBarHeight );
    
    self.mainScrollView.contentSize = CGSizeMake(kScreenW * self.childViewControllers.count, _mainScrollView.height);
    
    for (int i = 0; i < self.childViewControllers.count; i++) {
        
        UIViewController * vc = self.childViewControllers[i];
        vc.view.backgroundColor = ZRRandomColor;
        vc.view.x = i * ZRScreenW;
        [self.mainScrollView addSubview:vc.view];
    }
    
}


#pragma mark - ----------------------- 生命周期 -----------------------

#pragma mark - ----------------------- 其他方法 -----------------------
#pragma mark - 初始化设置
- (void)prepareSetting{
    
    self.lampBarY = _lampBarY ? _lampBarY : kNavBarHeight;
    self.lampBarHeight = _lampBarHeight ? _lampBarHeight : 40;
    self.lampItemWidth = _lampItemWidth ? _lampItemWidth : 60;
    self.selectedIndex = 0;
    self.indicatorHeight = _indicatorHeight ? _indicatorHeight : 3;
    
}

#pragma mark - 动画
/** 拖拽动画 */
- (void)dragAnimationWithOffset:(CGPoint)offset{
    
    int index = (int)(offset.x / kScreenW);
    CGFloat offsetRate = (offset.x / kScreenW) - index;
    CGFloat max = _lampItemWidth + _lampItemGap;
    CGFloat left_X = index * max;
    CGFloat itemScal =  (max + _lampItemWidth) / _lampItemWidth;
    
    if (0 < offsetRate && offsetRate <= 0.5) {
    
        self.indicatorView.transform = CGAffineTransformMakeTranslation(left_X + max * offsetRate , 0);
        
        self.indicatorView.transform = CGAffineTransformScale(self.indicatorView.transform, 1 + (itemScal - 1) * offsetRate * 2, 1);
        
    }else if(0.5 < offsetRate && offsetRate <= 1){
        
        self.indicatorView.transform = CGAffineTransformMakeTranslation((left_X + 0.5 * max ) + max * (offsetRate - 0.5 ), 0);
        
        self.indicatorView.transform = CGAffineTransformScale(self.indicatorView.transform, 2 + _lampItemGap / _lampItemWidth - (itemScal - 1) * (offsetRate - 0.5) * 2, 1);

    }

}

/** 点击动画 */
- (void)selectAnimationWithItem:(NSInteger)item{     ZRWeakSelf
    
        [UIView animateWithDuration:0.25 animations:^{

          weakSelf.indicatorView.transform = CGAffineTransformMakeTranslation(item * (weakSelf.lampItemWidth + weakSelf.lampItemGap), 0);
        }];
}

#pragma mark - ----------------------- 代理方法 -----------------------
#pragma mark - CollectionView Delegate && DataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZRLampCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:id_cell forIndexPath:indexPath];
    
    UIViewController * vc = self.viewControllers[indexPath.item];
    cell.lampBarItem = vc.lampBarItem;
    cell.isSelected = indexPath.item == _selectedIndex ? YES : NO;
    
    cell.backgroundColor = ZRRandomColor;
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.childViewControllers.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.item == _selectedIndex) return;
    self.isSelectedAnimation = YES;
    
    [self selectAnimationWithItem:indexPath.item];
    
    [self.mainScrollView setContentOffset:CGPointMake(indexPath.item * ZRScreenW, 0) animated:NO];
    
    self.selectedIndex = (int)indexPath.item;
    
    [collectionView reloadData];
}


#pragma mark - ----------------------- 活动监听 -----------------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if ([scrollView isEqual:self.lampCollectionView]) return;
  
    if (!_indicatorView.isHidden && _isSelectedAnimation == NO) {
        
        [self dragAnimationWithOffset:scrollView.contentOffset];
    }
    self.isSelectedAnimation = NO;
}

/** 滑动结束:认为拖拽 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int item = scrollView.contentOffset.x / kScreenW;
    if (item == _selectedIndex || [scrollView isEqual:self.lampCollectionView]) return;

    self.selectedIndex = item;
    [self.lampCollectionView reloadData];
    
    [self.lampCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}


#pragma mark - ---------------------- set & get ----------------------
#pragma mark - 标签栏
- (UICollectionView *)lampCollectionView{
    if (!_lampCollectionView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 5;
        flowLayout.minimumInteritemSpacing = 30;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(60,40 - 3 - 2);
        flowLayout.sectionInset = UIEdgeInsetsMake(- 10, 0, 0, 0);
        
        
        _flowLayout = flowLayout;
        
        _lampCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, _lampBarHeight) collectionViewLayout:flowLayout];
        _lampCollectionView.backgroundColor = [UIColor clearColor];
        _lampCollectionView.pagingEnabled = NO;
        _lampCollectionView.showsHorizontalScrollIndicator = NO;
        _lampCollectionView.showsVerticalScrollIndicator = NO;
        _lampCollectionView.dataSource = self;
        _lampCollectionView.delegate = self;
        _lampCollectionView.alwaysBounceHorizontal = YES;
        _lampCollectionView.scrollsToTop = NO;
        
    
        [_lampCollectionView registerClass:[ZRLampCollectionViewCell class] forCellWithReuseIdentifier:id_cell];
    }
    
    return _lampCollectionView;
    
}

#pragma mark - 指示器
- (UIView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 , 21, 3)];
        _indicatorView.backgroundColor = [UIColor orangeColor];
        _indicatorView.layer.cornerRadius = 5;
        _indicatorView.layer.masksToBounds = YES;
 
    }
    return _indicatorView;
}

#pragma mark - 显示区域(滚动图)
- (UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenW)];
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.delegate = self;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.showsVerticalScrollIndicator = NO;
    }
    return _mainScrollView;
}


#pragma mark - 设置 标签数组
- (void)setViewControllers:(NSArray *)viewControllers{
    _viewControllers = viewControllers;
    
    for (int i = 0; i < viewControllers.count; i++) {
        
        if (![viewControllers[i] isKindOfClass:[UIViewController class]]) {
            NSLog(@"ZRLampTabController 提示:您添加的控制器可能不是 【UIViewController】类型");
            return;
        }
        
        [self addChildViewController:viewControllers[i]];
    }

}

#pragma mark - 设置 标签栏高度
- (void)setLampBarHeight:(CGFloat)lampBarHeight{
    _lampBarHeight = lampBarHeight;

    [self.view layoutIfNeeded];
    self.flowLayout.itemSize = CGSizeMake(_lampItemWidth,_lampBarHeight - _indicatorHeight - 10);
    [self.lampCollectionView reloadData];

}

#pragma mark - 设置 标签栏 Y
- (void)setLampBarY:(CGFloat)lampBarY{
    _lampBarY = lampBarY;
    
    [self.view layoutIfNeeded];
    [self.lampCollectionView reloadData];
}

#pragma mark - 设置 标签栏位置
- (void)setLampBarFrame:(CGRect)lampBarFrame{
    _lampBarFrame = lampBarFrame;
    
    _lampBarY = lampBarFrame.origin.y;
    _lampBarHeight = lampBarFrame.size.height;
    [self.view layoutIfNeeded];
    [self.lampCollectionView reloadData];
}

#pragma mark - 设置 是否允许滚动
- (void)setLampBarScrollEnabled:(BOOL)lampBarScrollEnabled{
    _lampBarScrollEnabled = lampBarScrollEnabled;
    
    self.lampCollectionView.scrollEnabled = lampBarScrollEnabled;
}

#pragma mark - 设置 标签宽度
- (void)setLampItemWidth:(CGFloat)lampItemWidth{
    _lampItemWidth = lampItemWidth;
    
    self.flowLayout.itemSize = CGSizeMake(_lampItemWidth,_lampBarHeight - _indicatorHeight - 10);
    [self.lampCollectionView reloadData];
}

#pragma mark - 设置 标签间距
- (void)setLampItemGap:(CGFloat)lampItemGap{
    _lampItemGap = lampItemGap;
    self.flowLayout.minimumLineSpacing = lampItemGap;
    [self.lampCollectionView reloadData];
}

#pragma mark - 设置 指示器高度
- (void)setIndicatorHeight:(CGFloat)indicatorHeight{
    
    _indicatorHeight = indicatorHeight > 10 ? 10 : indicatorHeight;
    [self.view layoutIfNeeded];
    
    self.flowLayout.itemSize = CGSizeMake(_lampItemWidth,_lampBarHeight - _indicatorHeight - 10);
    [self.lampCollectionView reloadData];
}

#pragma mark -  设置 指示器隐藏/显示
- (void)setShowIndicator:(BOOL)showIndicator{
    _showIndicator = showIndicator;
    self.indicatorView.hidden = showIndicator;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

@implementation UIViewController (ZRLampBarItem)

- (ZRLampBarItem *)lampBarItem {
    
    return objc_getAssociatedObject(self, @selector(lampBarItem));
}

- (void)setLampBarItem:(ZRLampBarItem *)lampBarItem{
    objc_setAssociatedObject(self, @selector(lampBarItem), lampBarItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end











